<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="filter-tags" v-if="hasActiveFilters">
      <span class="filter-label">已选条件：</span>
      <el-tag
        v-if="query.status"
        closable
        @close="clearFilter('status')"
        size="small"
        class="filter-tag"
        :type="getStatusType(query.status)"
      >
        状态: {{ query.status }}
      </el-tag>
      <el-tag
        v-if="query.isDisputed"
        closable
        @close="clearFilter('isDisputed')"
        size="small"
        class="filter-tag"
        type="danger"
      >
        争议订单
      </el-tag>
      <el-tag
        v-if="query.buyerId"
        closable
        @close="clearFilter('buyerId')"
        size="small"
        class="filter-tag"
      >
        买家ID: {{ query.buyerId }}
      </el-tag>
      <el-tag
        v-if="query.sellerId"
        closable
        @close="clearFilter('sellerId')"
        size="small"
        class="filter-tag"
      >
        卖家ID: {{ query.sellerId }}
      </el-tag>
      <el-tag
        v-if="query.productId"
        closable
        @close="clearFilter('productId')"
        size="small"
        class="filter-tag"
      >
        商品ID: {{ query.productId }}
      </el-tag>
      <el-tag
        v-if="query.startDate || query.endDate"
        closable
        @close="clearDateFilter()"
        size="small"
        class="filter-tag"
      >
        下单时间: {{ query.startDate || "-" }} 至 {{ query.endDate || "-" }}
      </el-tag>
      <el-button type="primary" link @click="resetFilters" size="small"
        >清空全部</el-button
      >
    </div>
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :viewFunc="handleView"
        :page-change="changePage"
        :loading="loading"
      >
        <template #toolbarBtn>
          <el-button type="primary" :icon="Download" @click="exportOrders"
            >导出</el-button
          >
        </template>
        <template #status="{ rows }">
          <el-tag :type="getStatusType(rows.status)">
            {{ rows.status }}
          </el-tag>
          <el-tag
            v-if="rows.disputeInfo?.isDisputed"
            type="danger"
            style="margin-left: 5px"
          >
            争议
          </el-tag>
        </template>
        <template #price="{ rows }">
          <span class="price">¥{{ rows.price?.toFixed(2) || 0 }}</span>
        </template>
        <template #product="{ rows }">
          <div class="product-info">
            <el-image
              v-if="rows.product?.images && rows.product.images.length > 0"
              :src="rows.product.images[0]"
              fit="cover"
              class="product-image"
              :preview-src-list="rows.product.images"
            />
            <div class="product-details">
              <div class="product-title">{{ rows.product?.title || "-" }}</div>
              <div class="product-condition">
                {{ rows.product?.condition || "" }}
              </div>
            </div>
          </div>
        </template>
        <template #buyer="{ rows }">
          <div class="user-info">
            <el-avatar v-if="rows.buyer?.avatar" :src="rows.buyer.avatar" :size="24">{{
              rows.buyer?.username?.substring(0, 1)
            }}</el-avatar>
            <span class="user-name">{{ rows.buyer?.username || "-" }}</span>
          </div>
        </template>
        <template #seller="{ rows }">
          <div class="user-info">
            <el-avatar v-if="rows.seller?.avatar" :src="rows.seller.avatar" :size="24">{{
              rows.seller?.username?.substring(0, 1)
            }}</el-avatar>
            <span class="user-name">{{ rows.seller?.username || "-" }}</span>
          </div>
        </template>
        <template #operator="{ rows }">
          <div class="order-actions">
            <el-button type="primary" size="default" @click="handleView(rows)"
              >查看</el-button
            >
            <el-button
              v-if="rows.status === '待见面交易' && !rows.isDisputed"
              type="danger"
              size="default"
              @click="handleForceCancel(rows)"
              >强制取消</el-button
            >
            <el-button
              v-if="!rows.disputeInfo?.isDisputed"
              type="warning"
              size="default"
              @click="openDisputeDialog(rows)"
              >标记争议</el-button
            >
            <el-button
              v-if="rows.disputeInfo?.isDisputed"
              type="success"
              size="default"
              @click="handleResolveDispute(rows)"
              >处理争议</el-button
            >
          </div>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      title="订单详情"
      v-model="detailVisible"
      width="800px"
      :close-on-click-modal="false"
      @closed="handleDialogClosed"
      :destroy-on-close="true"
    >
      <el-tabs v-model="activeTab" v-loading="detailLoading">
        <el-tab-pane label="订单信息" name="order">
          <TableDetail :data="viewData" :loading="detailLoading"></TableDetail>
        </el-tab-pane>
        <el-tab-pane label="商品信息" name="product">
          <TableDetail :data="productData" :loading="detailLoading"></TableDetail>
        </el-tab-pane>
        <el-tab-pane label="买家/卖家信息" name="users">
          <div class="users-info">
            <div class="user-card">
              <h3>买家信息</h3>
              <TableDetail :data="buyerData" :loading="detailLoading"></TableDetail>
            </div>
            <div class="user-card">
              <h3>卖家信息</h3>
              <TableDetail :data="sellerData" :loading="detailLoading"></TableDetail>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作记录" name="logs" v-if="actionLogs.length > 0">
          <el-timeline>
            <el-timeline-item
              v-for="(log, index) in actionLogs"
              :key="index"
              :timestamp="formatDate(log.timestamp)"
              :type="getLogType(log.action)"
            >
              <h4>{{ log.action }}</h4>
              <p v-if="log.operator">操作人: {{ log.operator }}</p>
              <p v-if="log.reason">原因: {{ log.reason }}</p>
              <p v-if="log.resolution">处理结果: {{ log.resolution }}</p>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog
      title="强制取消订单"
      v-model="cancelVisible"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @closed="handleCancelDialogClosed"
    >
      <el-form ref="cancelForm" :model="cancelForm" label-width="100px" v-if="cancelForm">
        <el-form-item label="订单编号">
          <span>{{ currentOrder.orderNumber || currentOrder._id }}</span>
        </el-form-item>
        <el-form-item label="取消原因" prop="reason" required>
          <el-input
            type="text"
            v-model="cancelForm.reason"
            placeholder="请输入强制取消的原因"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForceCancel" :loading="submitLoading">
            确认取消
          </el-button>
          <el-button @click="handleCloseCancelDialog">取消</el-button>
        </el-form-item>
      </el-form>
      <div v-else class="dialog-loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>
    </el-dialog>
    <el-dialog
      title="标记争议订单"
      v-model="disputeState.visible"
      width="600px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form
        ref="formRef"
        :model="disputeState.form"
        :rules="disputeState.rules"
        label-width="100px"
        v-loading="disputeState.loading"
      >
        <el-form-item label="订单编号" prop="orderNumber">
          <span class="order-number">
            {{ currentOrder.orderNumber || currentOrder._id }}
          </span>
        </el-form-item>

        <el-form-item label="争议原因" prop="reason">
          <el-input
            v-model="disputeState.form.reason"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请详细描述争议原因（10-500字）"
            clearable
            show-word-limit
            maxlength="500"
            @keydown.enter.prevent="submitDispute"
          />
        </el-form-item>

        <el-form-item class="dialog-footer">
          <el-button
            type="primary"
            :loading="disputeState.loading"
            @click="submitDispute"
          >
            提交标记
          </el-button>
          <el-button
            :disabled="disputeState.loading"
            @click="disputeState.visible = false"
          >
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="处理争议订单"
      v-model="resolveVisible"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @closed="handleResolveDialogClosed"
    >
      <el-form
        ref="resolveForm"
        :model="resolveForm"
        label-width="100px"
        v-if="resolveForm"
      >
        <el-form-item label="订单编号">
          <span>{{ currentOrder.orderNumber || currentOrder._id }}</span>
        </el-form-item>
        <el-form-item label="处理操作" prop="action" required>
          <el-select v-model="resolveForm.action" placeholder="请选择处理操作">
            <el-option label="保持原状" value="保持原状"></el-option>
            <el-option label="完成订单" value="完成订单"></el-option>
            <el-option label="取消订单" value="取消订单"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理结果" prop="resolution" required>
          <el-input
            type="text"
            v-model="resolveForm.resolution"
            placeholder="请输入处理结果说明"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitResolveDispute"
            :loading="submitLoading"
          >
            确认处理
          </el-button>
          <el-button @click="handleCloseResolveDialog">取消</el-button>
        </el-form-item>
      </el-form>
      <div v-else class="dialog-loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Download, View, Loading } from "@element-plus/icons-vue";
import request from "@/utils/request";
import { FormOptionList } from "@/types/form-option";
import _ from "lodash";
import type { FormInstance } from "element-plus";

// 导入组件
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";

export default {
  name: "system-order",
  components: {
    TableCustom,
    TableDetail,
    TableSearch,
    Download,
    View,
    Loading,
  },
  setup() {
    // 查询相关
    const query = reactive({
      status: "",
      buyerId: "",
      sellerId: "",
      productId: "",
      startDate: "",
      endDate: "",
      isDisputed: "",
      sort: "createdAt",
      order: "desc",
    });

    // 表单引用
    const formRef = ref<FormInstance>();

    const searchOpt = ref<FormOptionList[]>([
      {
        type: "select",
        label: "订单状态：",
        prop: "status",
        opts: [
          { label: "全部", value: "" },
          { label: "待见面交易", value: "待见面交易" },
          { label: "已完成", value: "已完成" },
          { label: "已取消", value: "已取消" },
          { label: "已强制取消", value: "已强制取消" },
        ],
      },
      {
        type: "select",
        label: "争议状态：",
        prop: "isDisputed",
        opts: [
          { label: "全部", value: "" },
          { label: "争议订单", value: "true" },
          { label: "非争议订单", value: "false" },
        ],
      },
      {
        type: "input",
        label: "买家ID：",
        prop: "buyerId",
        placeholder: "输入买家ID",
      },
      {
        type: "input",
        label: "卖家ID：",
        prop: "sellerId",
        placeholder: "输入卖家ID",
      },
      {
        type: "input",
        label: "商品ID：",
        prop: "productId",
        placeholder: "输入商品ID",
      },
      {
        type: "datepicker",
        label: "下单时间：",
        prop: "datepicker",
        format: "YYYY-MM-DD",
        onChange: (val: [string, string]) => {
          if (val) {
            query.startDate = val[0];
            query.endDate = val[1];
          } else {
            query.startDate = "";
            query.endDate = "";
          }
        },
      },
    ]);

    // 表格相关
    const loading = ref(false);
    const columns = ref([
      { type: "index", label: "序号", width: 55, align: "center" },
      { prop: "_id", label: "订单ID", width: 120 },
      {
        prop: "product",
        label: "商品",
        width: 220,
        slotName: "product",
      },
      {
        prop: "price",
        label: "价格",
        width: 80,
        formatter: (row: any) => {
          return `¥${row.price?.toFixed(2) || 0}`;
        },
      },
      {
        prop: "buyer",
        label: "买家",
        width: 120,
        slotName: "buyer",
      },
      {
        prop: "seller",
        label: "卖家",
        width: 120,
        slotName: "seller",
      },
      {
        prop: "status",
        label: "订单状态",
        slotName: "status",
        width: 150,
      },
      {
        prop: "formattedDate",
        label: "创建时间",
        width: 220,
      },
      { prop: "operator", label: "操作", width: 300 },
    ]);

    // 状态对应的标签类型
    const getStatusType = (status: string) => {
      const typeMap: Record<string, string> = {
        待见面交易: "warning",
        已完成: "success",
        已取消: "info",
        已强制取消: "danger",
      };
      return typeMap[status] || "";
    };

    // 日志操作对应的类型
    const getLogType = (action: string) => {
      if (action.includes("取消")) return "danger";
      if (action.includes("完成")) return "success";
      if (action.includes("争议")) return "warning";
      return "primary";
    };

    // 格式化日期
    const formatDate = (dateStr: string) => {
      if (!dateStr) return "-";
      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return "-"; // 无效日期
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(date.getDate()).padStart(2, "0")} ${String(date.getHours()).padStart(
          2,
          "0"
        )}:${String(date.getMinutes()).padStart(2, "0")}`;
      } catch (e) {
        console.error("日期格式化错误:", e);
        return "-";
      }
    };

    // 格式化会面时间
    const formatMeetingTime = (dateStr: string) => {
      if (!dateStr) return "-";
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date
        .getDate()
        .toString()
        .padStart(2, "0")} ${date
        .getHours()
        .toString()
        .padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
    };

    // 判断是否有激活的筛选条件
    const hasActiveFilters = computed(() => {
      return (
        !!query.status ||
        !!query.buyerId ||
        !!query.sellerId ||
        !!query.productId ||
        !!query.isDisputed ||
        !!query.startDate ||
        !!query.endDate
      );
    });

    // 清除单个筛选条件
    const clearFilter = (field: string) => {
      query[field] = "";
      getData();
    };

    // 清除日期筛选
    const clearDateFilter = () => {
      query.startDate = "";
      query.endDate = "";
      getData();
    };

    // 重置所有筛选条件
    const resetFilters = () => {
      Object.keys(query).forEach((key) => {
        if (key !== "sort" && key !== "order") {
          query[key] = "";
        }
      });
      getData();
    };

    const handleSearch = () => {
      changePage(1);
    };

    const page = reactive({
      index: 1,
      size: 10,
      total: 0,
    });

    const tableData = ref<any[]>([]);

    const getData = async () => {
      try {
        loading.value = true;
        const params = {
          page: page.index,
          limit: page.size,
          ...query,
        };

        const res = await request.get("/api/orders/admin/orders", params);
        if (res.success) {
          console.log("原始订单数据:", res.data);

          // 处理日期格式
          const processedOrders = (res.data.orders || []).map((order) => {
            const processedOrder = {
              ...order,
              // 添加disputeInfo字段平铺
              isDisputed: order.disputeInfo?.isDisputed || false,
              disputeReason: order.disputeInfo?.reason,
            };

            // 处理创建时间
            if (order.createdAt) {
              try {
                const date = new Date(order.createdAt);
                if (!isNaN(date.getTime())) {
                  processedOrder.formattedDate = `${date.getFullYear()}-${String(
                    date.getMonth() + 1
                  ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(
                    date.getHours()
                  ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
                } else {
                  processedOrder.formattedDate = "-";
                }
              } catch (e) {
                console.error("日期处理错误:", e);
                processedOrder.formattedDate = "-";
              }
            } else {
              processedOrder.formattedDate = "-";
            }

            return processedOrder;
          });

          console.log("处理后的订单数据:", processedOrders);
          tableData.value = processedOrders;
          page.total = res.data.total || 0;
        } else {
          ElMessage.error(res.message || "获取订单列表失败");
        }
      } catch (error) {
        console.error("获取订单列表失败:", error);
        ElMessage.error("获取订单列表失败");
      } finally {
        loading.value = false;
      }
    };

    const changePage = (val: number) => {
      page.index = val;
      getData();
    };

    // 导出订单
    const exportOrders = () => {
      ElMessageBox.confirm("确定要导出当前筛选条件下的订单数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          ElMessage.success("导出成功");
          // 这里可以添加实际的导出逻辑
        })
        .catch(() => {});
    };

    // 查看详情相关
    const detailVisible = ref(false);
    const detailLoading = ref(false);
    const activeTab = ref("order");
    const viewData = ref({
      row: {},
      list: [],
    });
    const productData = ref({
      row: {},
      list: [],
    });
    const buyerData = ref({
      row: {},
      list: [],
    });
    const sellerData = ref({
      row: {},
      list: [],
    });
    const actionLogs = ref<any[]>([]);

    const handleView = async (row: any) => {
      if (detailLoading.value) return; // 防止重复点击

      try {
        detailLoading.value = true;
        activeTab.value = "order";

        // 预先清空数据，防止显示上一次的数据造成闪烁
        viewData.value = { row: {}, list: [] };
        productData.value = { row: {}, list: [] };
        buyerData.value = { row: {}, list: [] };
        sellerData.value = { row: {}, list: [] };
        actionLogs.value = [];

        console.log("发送请求前，订单ID:", row._id);

        // 获取订单详情
        const res = await request.get(`/api/orders/admin/orders/${row._id}`);
        console.log("API响应:", res);

        if (res.success) {
          const orderDetail = res.data.order || res.data;
          console.log("订单详情数据:", orderDetail);

          // 处理日期
          if (orderDetail.createdAt) {
            try {
              const date = new Date(orderDetail.createdAt);
              if (!isNaN(date.getTime())) {
                orderDetail.formattedDate = `${date.getFullYear()}-${String(
                  date.getMonth() + 1
                ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(
                  date.getHours()
                ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
              } else {
                orderDetail.formattedDate = "-";
              }
            } catch (e) {
              console.error("日期处理错误:", e);
              orderDetail.formattedDate = "-";
            }
          } else {
            orderDetail.formattedDate = "-";
          }

          // 处理更新时间
          if (orderDetail.updatedAt) {
            try {
              const date = new Date(orderDetail.updatedAt);
              if (!isNaN(date.getTime())) {
                orderDetail.formattedUpdatedAt = `${date.getFullYear()}-${String(
                  date.getMonth() + 1
                ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(
                  date.getHours()
                ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
              } else {
                orderDetail.formattedUpdatedAt = "-";
              }
            } catch (e) {
              console.error("日期处理错误:", e);
              orderDetail.formattedUpdatedAt = "-";
            }
          } else {
            orderDetail.formattedUpdatedAt = "-";
          }

          // 订单信息
          viewData.value.row = {
            ...orderDetail,
            meetingLocation: orderDetail.meetingInfo?.location,
            meetingTime: formatMeetingTime(orderDetail.meetingInfo?.time),
            contactPhone: orderDetail.contactInfo?.phone,
            contactWechat: orderDetail.contactInfo?.wechat,
            adminActionReason: orderDetail.adminAction?.reason,
            adminActionTime: formatDate(orderDetail.adminAction?.actionTime),
            adminName: orderDetail.adminAction?.adminId?.username,
            disputeReason: orderDetail.disputeInfo?.reason,
            reportedBy: orderDetail.disputeInfo?.reportedBy,
            reportedAt: formatDate(orderDetail.disputeInfo?.reportedAt),
          };

          viewData.value.list = [
            { prop: "_id", label: "订单ID" },
            { prop: "status", label: "订单状态" },
            {
              prop: "price",
              label: "订单金额",
              formatter: (val: number) => `¥${val?.toFixed(2) || 0}`,
            },
            { prop: "meetingLocation", label: "交易地点" },
            { prop: "meetingTime", label: "交易时间" },
            { prop: "contactPhone", label: "联系电话" },
            { prop: "contactWechat", label: "联系微信" },
            {
              prop: "adminActionReason",
              label: "处理原因",
              formatter: (val: string) => val || "无",
            },
            {
              prop: "adminActionTime",
              label: "处理时间",
              formatter: (val: string) => val || "-",
            },
            {
              prop: "adminName",
              label: "处理人",
              formatter: (val: string) => val || "系统自动处理",
            },
            {
              prop: "disputeReason",
              label: "争议原因",
              formatter: (val: string) => val || "无",
            },
            {
              prop: "reportedBy",
              label: "发起方",
              formatter: (val: string) => {
                const map: Record<string, string> = {
                  buyer: "买家",
                  seller: "卖家",
                  system: "系统",
                };
                return map[val] || val;
              },
            },
            {
              prop: "reportedAt",
              label: "发起时间",
              formatter: (val: string) => val || "-",
            },
            { prop: "formattedDate", label: "创建时间" },
          ];

          // 商品信息
          if (orderDetail.product) {
            productData.value.row = {
              ...orderDetail.product,
              sellerInfo: orderDetail.product.seller?.username,
            };
            productData.value.list = [
              { prop: "_id", label: "商品ID" },
              { prop: "title", label: "商品标题" },
              {
                prop: "price",
                label: "价格",
                formatter: (val: number) => `¥${val?.toFixed(2) || 0}`,
              },
              { prop: "category", label: "分类" },
              { prop: "condition", label: "成色" },
              { prop: "sellerInfo", label: "卖家" },
            ];
          }

          // 买家信息
          if (orderDetail.buyer) {
            buyerData.value.row = { ...orderDetail.buyer };
            buyerData.value.list = [
              { prop: "_id", label: "买家ID" },
              { prop: "username", label: "用户名" },
              { prop: "email", label: "邮箱" },
              { prop: "phone", label: "手机号" },
            ];
          }

          // 卖家信息
          if (orderDetail.seller) {
            sellerData.value.row = { ...orderDetail.seller };
            sellerData.value.list = [
              { prop: "_id", label: "卖家ID" },
              { prop: "username", label: "用户名" },
              { prop: "email", label: "邮箱" },
              { prop: "phone", label: "手机号" },
            ];
          }

          // 操作记录
          if (orderDetail.actionLogs && orderDetail.actionLogs.length > 0) {
            actionLogs.value = orderDetail.actionLogs;
          }

          // 获取数据后再显示弹窗
          detailVisible.value = true;
        } else {
          ElMessage.error(res.message || "获取订单详情失败");
          detailVisible.value = false;
        }
      } catch (error) {
        console.error("获取订单详情失败:", error);
        ElMessage.error("获取订单详情失败");
        detailVisible.value = false;
      } finally {
        detailLoading.value = false;
      }
    };

    // 强制取消订单相关
    const cancelVisible = ref(false);
    const cancelForm = reactive({
      reason: "",
    });
    const currentOrder = ref<any>({});
    const submitLoading = ref(false);

    const handleForceCancel = async (row: any) => {
      try {
        // 确保cancelForm是一个有效对象
        if (!cancelForm || typeof cancelForm !== "object") {
          // 重新初始化cancelForm
          Object.assign(cancelForm, { reason: "" });
        } else {
          // 重置表单
          cancelForm.reason = "";
        }

        // 深度复制当前行数据，避免引用问题
        currentOrder.value = JSON.parse(JSON.stringify(row));

        // 使用nextTick确保DOM更新，然后再显示对话框
        await nextTick();

        // 显示对话框
        cancelVisible.value = true;

        console.log("打开强制取消对话框，currentOrder:", currentOrder.value);
      } catch (error) {
        console.error("打开强制取消对话框失败:", error);
        ElMessage.error("打开对话框失败，请重试");
      }
    };

    // 关闭强制取消对话框
    const handleCloseCancelDialog = () => {
      console.log("关闭强制取消对话框");
      // 先关闭对话框
      cancelVisible.value = false;
    };

    // 强制取消对话框关闭后的回调
    const handleCancelDialogClosed = () => {
      console.log("强制取消对话框已完全关闭");
      // 重置表单内容
      cancelForm.reason = "";
      // 重置当前订单对象
      currentOrder.value = {};
    };

    const submitForceCancel = async () => {
      if (!cancelForm.reason) {
        ElMessage.warning("请输入取消原因");
        return;
      }

      try {
        submitLoading.value = true;
        const res = await request.put(
          `/api/orders/admin/orders/${currentOrder.value._id}/force-cancel`,
          cancelForm
        );
        if (res.success) {
          ElMessage.success("订单已强制取消");
          cancelVisible.value = false;
          getData(); // 刷新数据
        } else {
          ElMessage.error(res.message || "操作失败");
        }
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      } finally {
        submitLoading.value = false;
      }
    };

    // 标记争议相关状态
    const disputeState = reactive({
      visible: false,
      loading: false,
      form: {
        reason: "",
      },
      rules: {
        reason: [
          { required: true, message: "必须输入争议原因", trigger: "blur" },
          { min: 10, message: "至少需要10个字符说明", trigger: "blur" },
          { max: 500, message: "最多不超过500个字符", trigger: "blur" },
        ],
      },
    });

    // 优化后的打开对话框方法
    const openDisputeDialog = async (row) => {
      try {
        disputeState.loading = true;
        currentOrder.value = JSON.parse(JSON.stringify(row));

        // 重置表单状态
        disputeState.form = { reason: "" };
        await nextTick();

        disputeState.visible = true;
      } catch (error) {
        console.error("打开失败:", error);
        ElMessage.error("打开对话框失败");
      } finally {
        disputeState.loading = false;
      }
    };

    // 提交方法（带防抖）
    const submitDispute = _.debounce(async () => {
      if (!disputeState.visible) return;

      try {
        disputeState.loading = true;

        // 手动触发表单验证
        const valid = await formRef.value?.validate();
        if (!valid) return;

        const res = await request.put(
          `/api/orders/admin/orders/${currentOrder.value._id}/mark-dispute`,
          { reason: disputeState.form.reason }
        );

        if (res.success) {
          ElMessage.success("标记成功");
          disputeState.visible = false;
          getData();
        }
      } catch (error) {
        console.error("提交失败:", error);
        ElMessage.error(error.response?.data?.message || "操作失败");
      } finally {
        disputeState.loading = false;
      }
    }, 300);

    // 处理争议相关
    const resolveVisible = ref(false);
    const resolveForm = reactive({
      resolution: "",
      action: "",
    });

    const handleResolveDispute = async (row: any) => {
      try {
        // 确保resolveForm是一个有效对象
        if (!resolveForm || typeof resolveForm !== "object") {
          // 重新初始化resolveForm
          Object.assign(resolveForm, {
            resolution: "",
            action: "保持原状",
          });
        } else {
          // 重置表单
          resolveForm.resolution = "";
          resolveForm.action = "保持原状";
        }

        // 深度复制当前行数据，避免引用问题
        currentOrder.value = JSON.parse(JSON.stringify(row));

        // 使用nextTick确保DOM更新，然后再显示对话框
        await nextTick();

        // 显示对话框
        resolveVisible.value = true;

        console.log("打开处理争议对话框，currentOrder:", currentOrder.value);
      } catch (error) {
        console.error("打开处理争议对话框失败:", error);
        ElMessage.error("打开对话框失败，请重试");
      }
    };

    // 关闭处理争议对话框
    const handleCloseResolveDialog = () => {
      console.log("关闭处理争议对话框");
      // 先关闭对话框
      resolveVisible.value = false;
    };

    // 处理争议对话框关闭后的回调
    const handleResolveDialogClosed = () => {
      console.log("处理争议对话框已完全关闭");
      // 重置表单内容
      resolveForm.resolution = "";
      resolveForm.action = "";
      // 重置当前订单对象
      currentOrder.value = {};
    };

    const submitResolveDispute = async () => {
      if (!resolveForm.resolution) {
        ElMessage.warning("请输入处理结果");
        return;
      }

      try {
        submitLoading.value = true;
        const res = await request.put(
          `/api/orders/admin/orders/${currentOrder.value._id}/resolve-dispute`,
          resolveForm
        );
        if (res.success) {
          ElMessage.success("争议订单已处理");
          resolveVisible.value = false;
          getData(); // 刷新数据
        } else {
          ElMessage.error(res.message || "操作失败");
        }
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      } finally {
        submitLoading.value = false;
      }
    };

    const handleDialogClosed = () => {
      // 重置对话框状态
      activeTab.value = "order";
      viewData.value = { row: {}, list: [] };
      productData.value = { row: {}, list: [] };
      buyerData.value = { row: {}, list: [] };
      sellerData.value = { row: {}, list: [] };
      actionLogs.value = [];
    };

    onMounted(() => {
      getData();
    });

    return {
      query,
      searchOpt,
      handleSearch,
      columns,
      tableData,
      page,
      loading,
      getStatusType,
      changePage,
      exportOrders,
      detailVisible,
      detailLoading,
      viewData,
      productData,
      buyerData,
      sellerData,
      actionLogs,
      handleView,
      activeTab,
      formatDate,
      formatMeetingTime,
      getLogType,
      // 筛选相关
      hasActiveFilters,
      clearFilter,
      clearDateFilter,
      resetFilters,
      // 强制取消相关
      cancelVisible,
      cancelForm,
      currentOrder,
      submitLoading,
      handleForceCancel,
      submitForceCancel,
      handleCloseCancelDialog,
      handleCancelDialogClosed,
      // 标记争议相关
      disputeState,
      openDisputeDialog,
      submitDispute,
      // 处理争议相关
      resolveVisible,
      resolveForm,
      handleResolveDispute,
      submitResolveDispute,
      handleCloseResolveDialog,
      handleResolveDialogClosed,
      // 图标
      Download,
      handleDialogClosed,
      formRef,
    };
  },
};
</script>

<style scoped>
.container {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.price {
  color: #ff6b6b;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.users-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.user-card {
  flex: 1;
  min-width: 320px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.user-card h3 {
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.filter-tags {
  margin: 10px 0;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 5px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  font-weight: bold;
  color: #606266;
}

.filter-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.product-details {
  display: flex;
  flex-direction: column;
}

.product-title {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 130px;
}

.product-condition {
  font-size: 12px;
  color: #909399;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.order-actions {
  display: flex;
  flex-wrap: nowrap;
  gap: 5px;
  white-space: nowrap;
}

@media screen and (max-width: 1280px) {
  .order-actions {
    flex-wrap: wrap;
  }
}

.no-data {
  color: #909399;
  font-style: italic;
}

.dialog-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px;
  gap: 10px;
  color: #909399;
}

.order-number {
  font-weight: 500;
  color: #409eff;
}

.dialog-footer {
  margin-top: 30px;
  text-align: right;
}

.el-textarea__inner {
  transition: all 0.3s;
  line-height: 1.5;
}
</style>
